package com.example.writelogdemo.utils;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.annotation.NonNull;


import com.blankj.utilcode.util.LogUtils;
import com.example.writelogdemo.app.LogApp;

import java.io.File;

/**
 * @ClassName: FileManager
 * @Description: java类作用描述
 * @Author: augus
 * @CreateDate: 2020/11/11 17:09
 */
public class FileManager {
    // 媒体模块根目录
    private static final String SAVE_MEDIA_ROOT_DIR = Environment.DIRECTORY_DCIM;
    // 媒体模块存储路径
    private static final String SAVE_MEDIA_DIR = SAVE_MEDIA_ROOT_DIR + "/WriteLog";
    // 媒体模块-图片存储路径
    private static final String SAVE_MEDIA_PHOTO_DIR = SAVE_MEDIA_DIR + "/photo";
    // 媒体模块-相机存储路径
    private static final String SAVE_MEDIA_VIDEO_DIR = SAVE_MEDIA_DIR + "/video";
    // 视频导出存储路径
    private static final String SAVE_MEDIA_EXPORT_DIR = SAVE_MEDIA_DIR + "/export";

    // 上传头像存储路径
    private static final String AVATAR_DIR = "/avatar";

    // log 目录
    private static final String LOG_DIR = "/log";

    // JPG压缩文件存储地址
    private static final String JPG_COMPRESS_DIR = "/compress";

    // 广告页存储地址
    private static final String ADVERTISE_DIR = "/advertise";

    // apk的安装目录
    private static final String APK_DOWNLOAD_PATH = "/apk";

    // 视频音乐、滤镜各种特效目录
    private static final String VIDEO_EDIT_DIR_PATH = "/VideoEdit";

    // 海报存储目录
    private static final String POSTER_FILE_PATH = "/poster/pic";

    // JPG后缀
    public static final String JPG_SUFFIX = ".jpg";
    // PNG后缀
    public static final String PNG_SUFFIX = ".png";
    // MP4后缀
    public static final String MP4_SUFFIX = ".mp4";
    // YUV后缀
    public static final String YUV_SUFFIX = ".yuv";
    // h264后缀
    public static final String H264_SUFFIX = ".h264";

    // 本地媒体文件筛选条件
    public static final String MEDIA_FILTER_CONDITION_STR = "PV_";

    /**
     * 获取文件存储根目录
     */
    public static String getStorageRootDir() {
        File filePath = LogApp.getInstance().getExternalFilesDir(null);
        String path;
        if (filePath != null) {
            path = filePath.getAbsolutePath();
        } else {
            path = LogApp.getInstance().getFilesDir().getAbsolutePath();
        }
        return path;
    }

    /**
     * 应用在内部存储中的files路径
     */
    public static String getInternalFileDir() {
        return LogApp.getInstance().getFilesDir().getAbsolutePath();
    }


    /**
     * 获取App私有存储根目录
     */
    public static String getAppRootDir() {
        String path = getStorageRootDir();
        FileUtils.createOrExistsDir(path);
        return path;
    }

    /**
     * 获取媒体根目录
     */
    public static String getMediaRootPath() {
        return getFolderDirPath(SAVE_MEDIA_ROOT_DIR);
    }

    /**
     * 获取外部存储相机根目录
     */
    public static String getCameraRootPath() {
        return getFolderDirPath(SAVE_MEDIA_DIR);
    }

    /**
     * 图片地址
     */
    public static String getCameraPhotoPath() {
        return getFolderDirPath(SAVE_MEDIA_PHOTO_DIR);
    }

    /**
     * 视频地址
     */
    public static String getCameraVideoPath() {
        return getFolderDirPath(SAVE_MEDIA_VIDEO_DIR);
    }

    /**
     * 视频导出地址
     */
    public static File getExportPath() {
        String fileName = "MY_" + System.currentTimeMillis() + MP4_SUFFIX;
        return new File(getFolderDirPath(SAVE_MEDIA_EXPORT_DIR), fileName);
    }

    /**
     * 头像地址
     */
    public static String getAvatarPath(String fileName) {
        String path;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            path = getFolderDirPath(SAVE_MEDIA_DIR + AVATAR_DIR);
        } else {
            path = getSaveDir(AVATAR_DIR);
        }
        return path + File.separator + fileName;
    }

    /**
     * 获取视频编辑目录
     */
    public static String getVideoEditDir() {
        return getSaveDir(VIDEO_EDIT_DIR_PATH);
    }

    /**
     * 获取APK下载目录
     */
    public static String getApkDownLoadDir() {
        return getSaveDir(APK_DOWNLOAD_PATH);
    }

    /**
     * 海报存储目录
     */
    public static String getPosterDir() {
        return getSaveDir(POSTER_FILE_PATH);
    }

    /**
     * 获取log存储路径
     */
    public static String getLogRootPath() {
        return getSaveDir(LOG_DIR);
    }

    /**
     * 获取jpg压缩文件路径
     */
    public static String getCompressJpgImagePath(String tms) {
        String compressDir = getSaveDir(JPG_COMPRESS_DIR);
        return compressDir + File.separator + tms + JPG_SUFFIX;
    }

    /**
     * 获取广告页 视频路径
     */
    public static String getAdvertiseVideoPath(String name) {
        String videoDir = getSaveDir(ADVERTISE_DIR);
        return videoDir + File.separator + name + MP4_SUFFIX;
    }

    public static String getAdvertiseImagePath(String name) {
        String videoDir = getSaveDir(ADVERTISE_DIR);
        return videoDir + File.separator + name + PNG_SUFFIX;
    }

    /**
     * 获取具体模块存储目录
     */
    public static String getSaveDir(@NonNull String directory) {
        String path = "";
        if (TextUtils.isEmpty(directory) || "/".equals(directory)) {
            path = "";
        } else if (directory.startsWith("/")) {
            path = directory;
        } else {
            path = "/" + directory;
        }
        path = getAppRootDir() + path;
        FileUtils.createOrExistsDir(path);
        return path;
    }

    /**
     * 创建文件目录
     *
     * @param dstDirPathToCreate 文件相对地址
     * @return 文件绝对地址
     */
    public static String getFolderDirPath(String dstDirPathToCreate) {
        File dstFileDir = new File(Environment.getExternalStorageDirectory(), dstDirPathToCreate);
        if (!dstFileDir.exists() && !dstFileDir.mkdirs()) {
            LogUtils.e("Failed to create file dir path--->" + dstDirPathToCreate);
            return null;
        }
        return dstFileDir.getAbsolutePath();
    }

    /**
     * 通过媒体文件Uri获取文件-Android 11兼容
     *
     * @param fileUri 文件Uri
     */
    public static File getMediaUri2File(Uri fileUri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = LogApp.getInstance().getContentResolver().query(fileUri, projection,
                null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                String path = cursor.getString(columnIndex);
                cursor.close();
                return new File(path);
            }
        }
        return null;
    }

    /**
     * 通过媒体文件地址获取Uri-Android 11兼容
     *
     * @param filePath 文件地址
     */
    public static Uri getMediaPath2Uri(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        Uri uriType, reallyUri = null;
        if (filePath.endsWith(MP4_SUFFIX)) {
            // 视频
            uriType = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else {
            // 图片
            uriType = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        }
        String whereValue = MediaStore.Video.Media.DATA + " like?";
        String argStr = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
        String[] argsValue = new String[]{"%" + argStr + "%"};
        Cursor cursor = LogApp.getInstance().getContentResolver().query(uriType, null,
                whereValue, argsValue, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                // 获取唯一的id
                long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                // 通过id构造Uri
                reallyUri = ContentUris.withAppendedId(uriType, id);
            }
            cursor.close();
        }
        return reallyUri;
    }

    /**
     * 简单插入媒体数据并返回Uri-Android 11兼容
     *
     * @param filePath 文件地址
     */
    public static Uri insertMediaPath2Uri(String filePath) {
        ContentValues values = new ContentValues();
        Uri uriType;
        String dataFormat;
        if (filePath.endsWith(MP4_SUFFIX)) {
            // 视频
            uriType = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            dataFormat = "video/mp4";
        } else {
            // 图片
            uriType = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            dataFormat = "image/jpeg";
        }
        values.put(MediaStore.Images.Media.DATA, filePath);
        values.put(MediaStore.Images.Media.MIME_TYPE, dataFormat);
        return LogApp.getInstance().getContentResolver().insert(uriType, values);
    }

    /**
     * 删除内媒体库文件
     *
     * @param path 文件地址
     */
    public static boolean deleteInnerMediaFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 兼容Android 11
            Uri reallyUri;
            if (path.contains("pvcamera/camera/")) {
                reallyUri = null;
            } else {
                reallyUri = getMediaPath2Uri(path);
            }
            if (reallyUri == null) {
                return false;
            }
            int deleteCode = LogApp.getInstance().getContentResolver().delete(reallyUri,
                    null, null);
            return deleteCode > 0;
        } else {
            if (file.isFile()) {
                return file.delete();
            }
            if (!file.isDirectory()) {
                return false;
            }
            File[] fileArray = file.listFiles();
            if (fileArray != null && fileArray.length > 0) {
                for (File f : fileArray) {
                    if (f.isFile()) {
                        f.delete();
                    } else if (f.isDirectory()) {
                        deleteInnerMediaFile(f.getAbsolutePath());
                    }
                }
            }
            return file.delete();
        }
    }

    /**
     * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
     *
     * @param context  上下文
     * @param imageUri 图片地址
     */
    public static String getImageAbsolutePath(Activity context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    /**
     * @param uri The Uri to checkRemote.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to checkRemote.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to checkRemote.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to checkRemote.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try (Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        }
        return null;
    }
}
